import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//Tcp的服务器
public class Tcpserver {
    private ServerSocket socket = null;

    public Tcpserver(int port) throws IOException {
        socket = new ServerSocket(port);//自己手动指定端口
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("启动服务器");
        while (true) {
            //连接服务器
            Socket serverSocket = socket.accept();
            work(serverSocket);
        }
    }

    public void work(Socket serverSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端建立连接!\n", serverSocket.getInetAddress().toString(), serverSocket.getPort());
        //获取请求
        //读取请求
        try (InputStream inputStream = serverSocket.getInputStream()) {
            //根据TCP协9议构成响应
            try (OutputStream outputStream = serverSocket.getOutputStream()) {
                //循环处理好每个请求，构成响应
                Scanner scanner = new Scanner(inputStream);
                while (true) {
                    if (!scanner.hasNext()) {
                        System.out.printf("[%s:%d] 客户端断开连接!\n", serverSocket.getInetAddress().toString(), serverSocket.getPort());
                        break;
                    }
                    //获取到请求
                    String request = scanner.next();
                    //构造响应
                    String response = process(request);
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);//打印
                    //刷新缓冲区
                    printWriter.flush();//相当于发送
                    System.out.printf("[%s:%d] req: %s, resp: %s\n", serverSocket.getInetAddress().toString(),
                            serverSocket.getPort(), request, response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }

    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        Tcpserver tcpserver = new Tcpserver(9090);
        tcpserver.start();
    }
}
